# coding=utf-8
#

import os
import json
import time

import concurrent.futures

from multiprocessing import Pool

from django.core.management.base import BaseCommand

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client
from tencentcloud.cvm.v20170312 import models

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent


#TX_API_AK = "AKID53SmxxlMkxxlMcT9ctRp10nMirnVzJQK"
#TX_API_SK = "iFZfYEhwxlLk2oQvOlz4A7vXyDIE1c1H"
TX_API_AK = "AKIDIarCd1C3HdwAU9zux7IjDqhCsegpGoP5"
TX_API_SK = "waHxZdfzSh8iIHGKd8xtUzfbgOTc7rfa"


def delete_agents_v2(endpoint, zone, server_list):
    """ """
    cred = credential.Credential(TX_API_AK, TX_API_SK)

    httpProfile = HttpProfile()
    httpProfile.endpoint = endpoint

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = cvm_client.CvmClient(cred, zone, clientProfile)

    req = models.TerminateInstancesRequest()

    params = {"InstanceIds": server_list,
              "ReleasePrepaidDataDisks": True}

    req.from_json_string(json.dumps(params))

    print(endpoint, zone, server_list)
    try:
        resp = client.TerminateInstances(req)
        print(resp)
    except Exception as msg:
        print(str(msg))

    time.sleep(1)


class Command(BaseCommand):
    help = "定时删除腾讯云的机器实例"

    def handle(self, *args, **options):
        """ 定时删除腾讯云机器实例 """
        task_name = "pid/daily_delete_tx_sh_agent"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            project_lists = [
                {"endpoint": "cvm.ap-shanghai.tencentcloudapi.com", "zone": "ap-shanghai", "cn_name": "上海"},
            ]

            for project_az_info in project_lists:

                # 腾讯云API初始化用的参数
                endpoint = project_az_info["endpoint"]
                zone = project_az_info["zone"]
                cn_name = project_az_info["cn_name"]

                print(endpoint, zone, cn_name)

                per_group = 100
                server_list = [x.instance_id for x in TidalAgent.objects.filter(idc="tencent", endpoint=endpoint, zone=zone)]
                with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:

                    # 提交任务到线程池，并收集Future对象  
                    splited_instance_lists = [server_list[i:i+per_group] for i in range(0, len(server_list), per_group)]
                    mt = {executor.submit(delete_agents_v2, endpoint, zone, instance_list): instance_list for instance_list in splited_instance_lists}
              
                    # 遍历Future对象，获取结果  
                    for future in concurrent.futures.as_completed(mt):
                        try:
                            data = future.result()  # 获取任务执行结果，如果任务抛出异常，这里会重新抛出  
                        except Exception as msg: 
                            print(str(msg))
